package Hot_100;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class T42_permute {

    @Test
    public void test1() {
        int[] nums = {1, 2, 3};
        List<List<Integer>> permute = permute(nums);
        System.out.println(permute);
    }

    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        boolean[] flag = new boolean[nums.length];  //标记数组，当选用某个数时应将其置为true
        DFS(nums, flag, new ArrayList<>());
        return res;
    }

    void DFS(int[] nums, boolean[] flag, ArrayList<Integer> ans) {
        if (ans.size() == nums.length) {
            res.add(new ArrayList<>(ans));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!flag[i]) {
                flag[i] = true;
                ans.add(nums[i]);
                DFS(nums, flag, ans);  //进入下一层递归

                //回溯
                flag[i] = false;
                ans.remove(ans.size() - 1); //记得要把元素弹出
            }
        }
    }
}
